//
//  LibraryAppDelegate.m
//  Library
//
//  Created by Johnnie Walker on 12/09/2008.
//  Copyright Random Sequence 2008. All rights reserved.
//

#import "LibraryAppDelegate.h"
#import "RSDB.h"

@implementation LibraryAppDelegate

@synthesize window;
@synthesize tabbarController;


- (id)init {
	if (self = [super init]) {
		// 
	}
	return self;
}


- (void)applicationDidFinishLaunching:(UIApplication *)application {
	
	// Setup Database
	
	RSDBDatabase *database = [self database];
	
#ifdef DEBUG_BUILD
	NSLog(@"Database version: %i",[database userVersion]);
#endif
	
	NSError *err;
	
	if ([database userVersion] > 0 && [database userVersion] != kRequiredDatabaseVersion) {
#ifdef DEBUG_BUILD
		NSLog(@"deleting the database - it's out of date");
#endif		
		
		[database close];
		// delete the persistent store
		[[NSFileManager defaultManager] removeItemAtPath:[database databasePath] error:&err];
		[database release];
		db = nil;
		// create a new one
		database = [self database];
	}
	
	[RSDB setDefaultDatabase:database];	
	
	// Load the data if required
	RSDBTable *forecastTable = [RSDB getTable:@"book"];
	
	if (!forecastTable.exists) {
		[database beginTransaction];
		//NSLog(@"wineTable doesn't exist");
		NSString *createSQL;		
		NSEnumerator *commands = [[[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"library" ofType:@"sql"]] componentsSeparatedByString:@"\n"] objectEnumerator];
		while(createSQL = [commands nextObject]) {
			if (![[createSQL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""]) {
				[database executeUpdate:createSQL];				
			}
		}
		[database commit];
		[database setUserVersion:kRequiredDatabaseVersion];
	}		
	
	// Configure and show the window
	[window addSubview:[tabbarController view]];
	[window makeKeyAndVisible];
}


- (void)applicationWillTerminate:(UIApplication *)application {
	// Save data if appropriate
}

- (RSDBDatabase *)database
{
	if (db == nil) {
		
		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDirectory = [paths objectAtIndex:0];		
		NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"library.db"];
		
		// NSLog(@"dbPath: %@",dbPath);
		
		db = [[RSDBDatabase databaseWithPath:dbPath] retain];
		if (![db open]) {
			NSLog(@"Could not open db.");
			return 0;
		}		
		
		//		[db setTraceExecution:YES];
		//		[db setLogsErrors:YES];
	}
	
	return db;
}

- (void)dealloc {
	[tabbarController release];
	[window release];
	[super dealloc];
}

@end
